package com.jrx.anytxn.param.controller.rights;

import com.google.common.collect.Maps;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.entity.PrRightsAndInterestsReq;
import com.jrx.anytxn.param.entity.PrRightsAndInterestsRes;
import com.jrx.anytxn.param.plugins.DeleteLog;
import com.jrx.anytxn.param.plugins.DeleteLogHelper;
import com.jrx.anytxn.param.service.rights.IPrRightsAndInterestsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.service.InfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 权益参数controller
 *
 * @author lbz
 */
@Api(tags = "权益参数API接口")
@RestController
@RequestMapping(value = "/param/rights")
public class RightsAndInterestsController {

    private static final Logger logger = LoggerFactory.getLogger(RightsAndInterestsController.class);

    @Autowired
    private InfoService infoService;
    @Autowired
    private IPrRightsAndInterestsService prRightsAndInterestsService;


    @ApiOperation(value = "根据租户ID和权益ID查询", notes = "根据租户ID和权益ID查询")
    @GetMapping(value = "/{tenantId}/{rightsId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "rightsId", value = "权益ID", required = true)
    })
    public TxnRespResult<PrRightsAndInterestsRes> getById(@PathVariable String tenantId,
                                                          @PathVariable String rightsId) {
        TxnRespResult<PrRightsAndInterestsRes> result = new TxnRespResult<>();
        PrRightsAndInterestsRes res;
        try {
            res = prRightsAndInterestsService.getByTenIdIdAndRightsId(tenantId, rightsId);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "新增权益参数", notes = "新增权益参数")
    @PostMapping("/save")
    public TxnRespResult<Integer> add(@RequestBody PrRightsAndInterestsReq prRightsAndInterestsReq) {
        TxnRespResult<Integer> result = new TxnRespResult<>();
        Integer res;
        try{
            prRightsAndInterestsReq.setRightsStatus("0");
            prRightsAndInterestsReq.setValidDays(30);
            prRightsAndInterestsReq.setInterestDiscountPayer("01");
            prRightsAndInterestsReq.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            prRightsAndInterestsReq.setUpdateBy(infoService.getUser().getUserName());
            res = prRightsAndInterestsService.addPrRightsAndInterests(prRightsAndInterestsReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "分页查询权益参数", notes = "分页查询权益参数")
    @PostMapping(value = "/pageNum/{pageNum}/pageSize/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = true)})
    public TxnRespResult<TxnPage<PrRightsAndInterestsRes>> getAllPageByTenId(@PathVariable("pageNum") Integer pageNum,
                                                                             @PathVariable("pageSize") Integer pageSize,
                                                                             @RequestBody PrRightsAndInterestsReq req) {
        TxnRespResult<TxnPage<PrRightsAndInterestsRes>> result = new TxnRespResult<>();
        try {
            req.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            TxnPage<PrRightsAndInterestsRes>  res = prRightsAndInterestsService.findAllPageByCondition(pageNum, pageSize, req);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "更新权益参数", notes = "更新权益参数")
    @PutMapping("/modify")
    public TxnRespResult<Integer> modifyPrRightsAndInterests(@RequestBody PrRightsAndInterestsReq req) {
        TxnRespResult<Integer> result = new TxnRespResult<>();
        Integer res;
        try {
            req.setUpdateBy(infoService.getUser().getUserName());
            res = prRightsAndInterestsService.modifyPrRightsAndInterests(req);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID和权益ID删除信息", notes = "根据租户ID和权益ID删除信息")
    @DeleteMapping(value = "/{tenantId}/{rightsId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "rightsId", value = "权益ID", required = true)
    })
    public TxnRespResult<Boolean> removeByTenIdAndRightsId(@PathVariable String tenantId, @PathVariable String rightsId) {
        TxnRespResult<Boolean> result = new TxnRespResult<>();
        try {
            DeleteLog deleteLog = new DeleteLog(infoService.getUser().getUserName());
            DeleteLogHelper.setDelleteHistory(deleteLog);

            Boolean flag =
                    prRightsAndInterestsService.removeByTenantIdAndRightsId(tenantId, rightsId);
            result.getSuccess(flag);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        } finally {
            DeleteLogHelper.clearLocalHistory();
        }
        return result;
    }

    @ApiOperation(value = "获得对账文件配置下拉信息", notes = "获得对账文件配置下拉信息")
    @GetMapping(value = "/list")
    public TxnRespResult<HashMap<String, List<PrRightsAndInterestsRes>>> getList() {
        TxnRespResult<HashMap<String, List<PrRightsAndInterestsRes>>> result = new TxnRespResult<>();
        String tenantId=String.valueOf(101);
        List<PrRightsAndInterestsRes> all = prRightsAndInterestsService.findAllByTenId(tenantId);
        HashMap<String, List<PrRightsAndInterestsRes>> sysCodeMap = Maps.newHashMap();
        sysCodeMap.put("listData", all);
        return result.getSuccess(sysCodeMap);
    }

    @ApiOperation(value = "根据机构号和租户ID查询权益参数", notes = "根据机构号和租户ID查询权益参数")
    @GetMapping(value = "/organizationId/{organizationId}")
    @ApiImplicitParam(name = "organizationId", value = "机构号", required = true)
    public TxnRespResult<ArrayList<PrRightsAndInterestsRes>> getByOrgId(@PathVariable String organizationId) {
        TxnRespResult<ArrayList<PrRightsAndInterestsRes>> result = new TxnRespResult<>();
        String tenantId=String.valueOf(infoService.getUser().getProjectId());
        List<PrRightsAndInterestsRes> list = prRightsAndInterestsService.getByOrgIdAndTenId(organizationId, tenantId);
        return result.getSuccess((ArrayList) list);
    }

    @ApiOperation(value = "根据权益资格类型查询待兑换权益列表", notes = "根据权益资格类型查询待兑换权益列表")
    @GetMapping(value = "/list/rightsType/{rightsType}")
    @ApiImplicitParam(name = "orgId", value = "机构号", required = true)
    public TxnRespResult<HashMap<String, List<PrRightsAndInterestsRes>>> getRightByRightsType(@PathVariable(value = "rightsType") String rightsType) {
        logger.debug("get getRightByRightsType start");
        TxnRespResult<HashMap<String, List<PrRightsAndInterestsRes>>> result = new TxnRespResult<>();

        List<PrRightsAndInterestsRes> prRightsAndInterestsResList;
        try {
            String tenantId=String.valueOf(infoService.getUser().getProjectId());
            prRightsAndInterestsResList = prRightsAndInterestsService.selectByTenIdAndRightsType(tenantId,rightsType);
            HashMap<String, List<PrRightsAndInterestsRes>> sysCodeMap = Maps.newHashMap();
            sysCodeMap.put("listData", prRightsAndInterestsResList);
            result.getSuccess(sysCodeMap);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        logger.debug("get getRightByRightsType end");
        return result;
    }
}
